<?php

namespace Fastapi\Qywx;
class Token
{
    private     $corpid;
    private     $corpsecret;
    public      $access_token;      //企业微信token
    public      $ticket;            //企业微信 jsapid token
    public function __construct(string $secret=null)
    {
        $this->corpid = Config::CORPID;
        if (empty($secret)){
            $this->corpsecret =  Config::SECRET;
        }else{
            $this->corpsecret = $secret;
        }
    }

    public function getAccessToken(){
        $path = dirname(__FILE__).DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR."$this->corpsecret.php";
        if (!is_file($path)){
            $data =  new \stdClass();
            $data->expire_time = 0;
        }else{
            $data = json_decode(file_get_contents($path));
        }
        if(!isset($data->expire_time) || $data->expire_time < time()) {
            $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$this->corpid}&corpsecret={$this->corpsecret}";
            $res = Http::get($url);
            if (!isset($res->errcode) || $res->errcode != 0){
                throw new Error($res->errmsg ?? '獲取企微TOKEN失败！');
            }
            $access_token = $res->access_token;
            $data->expire_time = time() + 7000;
            $data->access_token = $access_token;
            file_put_contents($path,json_encode($data));
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    /**
     *获取jsapi  ticket值
     */
    public function GetJsapiTicket(){
        $name       = $this->corpsecret.'qywxJsapiTicket';
        $ticket =  Cache::get($name);
        if ($ticket){
            return $ticket;
        }
//        $url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=".$this->GetAccessToken()."&type=agent_config";
        $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=".$this->GetAccessToken();
        $res = Http::get($url);
        if ($res->errcode==0){
            $this->ticket = $res->ticket;
            Cache::set($name,$this->ticket,7200);
            return $this->ticket;
        }else{
            return false;
        }
    }

    /**
     *获取jsapi 应用的 ticket值
     */
    public function GetJsapiTicketAgent(){
        $name = $this->corpsecret.'agentQywxJsapiTicket';
        $ticket =  Cache::get($name);
        if ($ticket){
            return $ticket;
        }
        $url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=".$this->GetAccessToken()."&type=agent_config";
        $res = Http::get($url);
        if ($res->errcode==0){
            $this->ticket = $res->ticket;
            Cache::set($name,$this->ticket,7200);
            return $this->ticket;
        }else{
            return false;
        }
    }

    /**
     *获取js-jdk 配置信息
     * $str 随机字符串
     * $appid 企业id
     * $agentid  企业微信的应用id （e.g. 1000247）
     * $url   需要调用的url
     */
    public function JdkConfig($str,$appid,$agentid,$url=''){
        $ticket = $this->GetJsapiTicket();
        $ticketAgent = $this->GetJsapiTicketAgent();

        $timestamp = time();
        $nonceStr = $str;

        $signature = "jsapi_ticket=$ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($signature);

        $signatureAgent = "jsapi_ticket=$ticketAgent&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signatureAgent = sha1($signatureAgent);

        $config = array();
        $config['appid']        = $appid;
        $config['timestamp']    = $timestamp;
        $config['nonceStr']     = $nonceStr;
        $config['signature']    = $signature;
        $config['signatureAgent']    = $signatureAgent;

        $config['agentid']      = $agentid;

        return $config;

    }




}